package api

import (
	"blog/library"
	"blog/models"
	"github.com/astaxie/beego/orm"
)

type CategoryController struct {
	baseController
}

func (c *CategoryController) List() {
	page, _ := c.GetInt("page", 1)
	limit, _ := c.GetInt("limit", 15)

	categoryList, total, _ := models.GetList(models.CategoryTable(), page, limit, orm.NewCondition(), "-Id")
	api := library.Api{}
	api.Data = categoryList
	api.Total = total
	c.Data["json"] = api
	c.ServeJSON()
}

func (c *CategoryController) Create() {
	params := c.Ctx.Request.PostForm
	name := params.Get("name")
	if models.Exist(models.CategoryTable(), orm.NewCondition().And("name", name)) {
		c.error("分类名称已重复")
	}
	category := models.NewCategory()
	category.Name = name
	if _, err := models.Create(category); err != nil {
		c.error(err.Error())
	}
	c.success([]int{})
}

func (c *CategoryController) Delete() {
	id, err := c.GetInt("id")
	if err != nil {
		c.error("传入错误的id")
	}
	if _, err := models.DeleteById(models.CategoryTable(), id); err != nil {
		c.error(err.Error())
	}
	c.success([]int{})
}

func (c *CategoryController) Edit() {
	params := c.Ctx.Request.PostForm
	name := params.Get("name")
	id, _ := c.GetInt64("id", -1)
	var condition *orm.Condition
	condition = orm.NewCondition().And("name", name).AndNot("id", id)
	if models.Exist(models.CategoryTable(), condition) {
		c.error("分类名称已重复")
	}
	category := models.NewCategory()
	category.Name = name
	category.Id = id
	if _, err := models.UpdateByCondition(category); err != nil {
		c.error(err.Error())
	}
	c.success([]int{})
}
